package no.ntnu.fp.model;

import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;

import no.ntnu.fp.storage.DBConnection;

public abstract class ActiveRecord {
	public abstract void save();
	public abstract void edit(int index);
	public abstract void delete();
	
	DBConnection db;
	PreparedStatement ps;
	
	public ActiveRecord() {
		db = new DBConnection();
	}
	
	public static boolean next(ResultSet rs) {
		try {
			return rs.next();
		} catch (SQLException e) {
			e.printStackTrace();
			return false;
		}
	}
	
	public static int getInt(ResultSet rs, String string) {
		try {
			return rs.getInt(string);
		} catch (SQLException e) {
			e.printStackTrace();
			return -1;
		}
	}
	
	public static String getString (ResultSet rs, String string) {
		try {
			return rs.getString(string);
		} catch (SQLException e) {
			e.printStackTrace();
			return null;
		}
	}
	
	public void setPreparedStatement(String query) {
		try {
			this.ps = db.preparedStatement(query);
		} catch (SQLException e) {
			e.printStackTrace();
		}
	}
	
	public void setString(int index, String value) {
		try {
			this.ps.setString(index, value);
		} catch (SQLException e) {
			e.printStackTrace();
		}
	}
	
	public void setInt(int index, int value) {
		try {
			this.ps.setInt(index, value);
		} catch (SQLException e) {
			e.printStackTrace();
		}
	}
	
	public void addExecuteAndClosePS() {
		try {
			ps.addBatch();
			ps.executeBatch();
			ps.close();
		} catch (SQLException e) {
			e.printStackTrace();
		}
	}
	
	public void closeDBConnection() {
		try {
			this.db.closeConnection();
		} catch (SQLException e) {
			e.printStackTrace();
		}
	}
	
	public static void closeDBConnection(DBConnection db) {
		try {
			db.closeConnection();
		} catch (SQLException e) {
			e.printStackTrace();
		}
	}
}